<template>
  <!-- 🔴 替换 <el-row> → <Row>，<el-col> → <Col>（iview 组件无 el- 前缀） -->
  <Row :gutter="16">
    <Col span="12">
      <div ref="bmiChart" class="chart-container"></div>
    </Col>
    <Col span="12">
      <div ref="exerciseChart" class="chart-container"></div>
    </Col>
  </Row>
</template>

<script>
import * as echarts from 'echarts'
import request from '@/utils/request'

export default {
  name: 'Charts',
  data() {
    return {
      weightData: [], // 后端获取的体重数据
      userHeight: 1.75 // 用户身高（可后续对接个人资料接口）
    }
  },
  mounted() {
    // 先获取后端数据，再初始化图表
    this.getWeightHistory()
      .then(() => {
        this.initBMIChart()
      })
    this.initExerciseChart()
  },
  methods: {
    async getWeightHistory() {
      try {
        const res = await request({
          url: '/weighthis/list',
          method: 'POST',
          data: { pageNum: 1, pageSize: 30 } // 获取最近30条体重记录
        })
        // 格式化数据：提取日期+体重，按日期排序
        this.weightData = res.records
          .map(item => ({
            date: item.recordDate,
            weight: item.weight
          }))
          .sort((a, b) => new Date(a.date) - new Date(b.date))
      } catch (error) {
        console.error('获取体重历史数据失败', error)
        // 🔴 用 iview 的 Notice 提示（避免 Element UI 的 Message）
        this.$Notice.error({ title: '错误', desc: '获取体重数据失败，请检查后端是否启动' })
      }
    },

    initBMIChart() {
      const chartDom = this.$refs.bmiChart
      if (!chartDom) return
      const myChart = echarts.init(chartDom)
      // 从体重数据提取日期和BMI
      const xData = this.weightData.map(item => item.date)
      const yData = this.weightData.map(item => 
        (item.weight / (this.userHeight * this.userHeight)).toFixed(1)
      )
      const option = {
        title: { text: 'BMI指数趋势', left: 'center', textStyle: { fontSize: 14 } },
        xAxis: { type: 'category', data: xData },
        yAxis: { type: 'value', min: Math.min(...yData) - 0.5, max: Math.max(...yData) + 0.5 },
        series: [{
          data: yData,
          type: 'line',
          symbol: 'circle',
          itemStyle: { color: '#2d8cf0' }
        }],
        grid: { left: '5%', right: '5%', bottom: '15%', containLabel: true }
      }
      myChart.setOption(option)
      // 监听窗口 resize
      window.addEventListener('resize', () => myChart.resize())
    },

    initExerciseChart() {
      const chartDom = this.$refs.exerciseChart
      if (!chartDom) return
      const myChart = echarts.init(chartDom)
      const option = {
        title: { text: '本周锻炼情况', left: 'center', textStyle: { fontSize: 14 } },
        xAxis: { type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] },
        yAxis: { type: 'value', name: '分钟' },
        series: [{
          data: [45, 30, 60, 0, 45, 75, 40],
          type: 'bar',
          itemStyle: { color: '#19be6b' }
        }],
        grid: { left: '5%', right: '5%', bottom: '10%', containLabel: true }
      }
      myChart.setOption(option)
      window.addEventListener('resize', () => myChart.resize())
    }
  }
}
</script>

<style lang="less" scoped>
.chart-container {
  width: 100%;
  height: 280px;
  background: #f8f9fa;
  border-radius: 4px;
}
</style>